package com.laboratory.manage.controller;



import com.laboratory.manage.utils.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@RestController
@RequestMapping("/File")
public class FileController {

    @Value("${file.upload-dir}")
    private String uploadPath;

    // 定义成员变量
    private static String filePath;


    @PostMapping("/Upload")
    public R fileupload(@RequestParam("file") MultipartFile file){
        String oldName = file.getOriginalFilename();
        //realPath是文件夹的路径
        String projectPath = new File("").getAbsolutePath();
        String codePath = projectPath.substring(0, projectPath.lastIndexOf(File.separator));

        //以时间进行命名
        String folderName = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yy-MM-dd"));
        //存储的路径
        String realPath = codePath +File.separator +uploadPath +File.separator+ folderName;
        //创建文件对象
        File folder = new File(realPath);
        if (!folder.exists()) {
            //文件不存在，重新创建一个文件
            folder.mkdirs();
        }

        //使用uuid进行替换 防止文件名重复
        String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));

        //存储的路径应该是newName
        String path = realPath + File.separator + newName;


        try {
            //封装文件对象
            file.transferTo(new File(folder, newName));
            filePath = path;
            return R.ok().put("path", filePath);
        } catch (IOException e) {
            //return new Result().setCode(500).setMessage("上传失败");
            return R.error();
        }
    }

    // 对外提供获取 filePath 变量的接口
    public static String getFilePath() {
        return filePath;
    }


}
